package com.yilin.tms.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.tms.core.commons.model.JpushClient;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.message.MessageData;
import com.yilin.tms.core.entity.message.PushRecord;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.hatch.HatchJpush;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.message.mapper.PushRecordMapper;
import com.yilin.tms.message.service.IPushService;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 推送服务
 *
 * @author zhangjinyuan
 * @date 2022/10/26
 */
@Service
@Transactional
public class PushService extends ServiceImpl<PushRecordMapper, PushRecord> implements IPushService {


    @Resource
    SocketService socketService;
    @Resource
    IUserRemote userRemote;
    @Resource
    PushRecordMapper pushRecordMapper;

    private Map<String, HatchJpush> _hatchJpushMap = new HashMap<>();

    public HatchJpush getHatchJpush(String platId) {
        if (_hatchJpushMap.get(platId)!=null && _hatchJpushMap.get(platId).getShipperAppKey()!=null) return _hatchJpushMap.get(platId);
        if (platId != null) _hatchJpushMap.put(platId, ParamUtil.isSuccess(userRemote.getJpushHatch(platId)));
        return _hatchJpushMap.get(platId);
    }

    /**
     * 根据日期删除消息记录
     */
    @Override
    public void deleteByDate(String startDate, String endDate) {
        pushRecordMapper.deleteByDate(startDate, endDate);
    }

    /**
     * 根据用户推送(socket+极光推送)
     */
    @Override
    public void sendNotificationByUser(Account toAccount, MessageData.MessageType messageType,
                                       MessageData.DataType dataType, String text, String originalUrl) {
        MessageData messageData = new MessageData();
        // 所有的系统推送 统一由 admin发送
        Account adminUser = ParamUtil.isSuccess(userRemote.getSystemAdminUser());
        messageData.setAccountName("系统");
        messageData.setAccountId(adminUser.getId());
        messageData.setAccountUserType(adminUser.getUserType());
        messageData.setAccountAvatar(adminUser.getAvatar());

        messageData.setToAccountId(toAccount.getId());
        messageData.setToAccountUserType(toAccount.getUserType());
        messageData.setToAccountName(toAccount.getName());
        messageData.setToAccountAvatar(toAccount.getAvatar());
        messageData.setSendTime(new Date());
        messageData.setMessageType(messageType);
        messageData.setDataType(dataType);
        messageData.setSendState(MessageData.SendState.wait);
        messageData.setViewState(MessageData.ViewState.view);
        messageData.setText(text);
        messageData.setOriginalUrl(originalUrl);
        try {
            //延时3秒发送
            Thread.sleep(3000);
            socketService.sendMessageToUser(messageData);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 按用户别名(即用户Id)推送
     */
    @Override
    public void sendMessageByAlias(String platId, UserType userType, String[] alias, String title, String text,
                                   Map<String, Object> extendDataMap) {
        //获取极光推送工具类
        JpushClient jpushClient;
        if (userType == UserType.shipperUser) {
            jpushClient = JpushClient.getInstance(userType, getHatchJpush(platId).getShipperAppKey(), getHatchJpush(platId).getShipperMasterSecret());
        } else {
            jpushClient = JpushClient.getInstance(userType, getHatchJpush(platId).getTruckerAppKey(), getHatchJpush(platId).getTruckerMasterSecret());
        }
        //生成推送记录
        PushRecord pushRecord = generatePushRecord(PushRecord.PushTarget.alias, Arrays.toString(alias),
                title, text, extendDataMap);
        //发送
        Map<String, Object> resultMap = jpushClient.sendToAlias(Arrays.asList(alias), pushRecord.getTitle(),
                pushRecord.getTitle(), pushRecord.getText(), pushRecord.getExtendData());
        pushRecord.setPushMsg((String) resultMap.get("pushResult"));
        if ((boolean) resultMap.get("success")) {
            pushRecord.setPushState(PushRecord.PushState.success);
        } else {
            pushRecord.setPushState(PushRecord.PushState.fail);
            pushRecord.setSendNumber(pushRecord.getSendNumber() + 1);
        }
        pushRecordMapper.insert(pushRecord);
    }

    /**
     * 按PushId推送
     */
    @Override
    public void sendMessageByPushId(String[] pushIds, String title, String text, Map<String, Object> extendDataMap) {
//        //获取极光推送工具类
//        JpushClient jpushClient = JpushClient.getInstance(appkey, mastersecret);
//        //生成推送记录
//        PushRecord pushRecord = generatePushRecord(PushRecord.PushTarget.pushId, Arrays.toString(pushIds), title,
//                text, extendDataMap);
//        //发送
//        Map<String, Object> resultMap = jpushClient.sendToRegistrationIds(Arrays.asList(pushIds), pushRecord.getTitle(),
//                pushRecord.getTitle(), pushRecord.getText(), pushRecord.getExtendData());
//        pushRecord.setPushMsg((String) resultMap.get("pushResult"));
//        if ((boolean) resultMap.get("success")) {
//            pushRecord.setPushState(PushRecord.PushState.success);
//        } else {
//            pushRecord.setPushState(PushRecord.PushState.fail);
//            pushRecord.setSendNumber(pushRecord.getSendNumber() + 1);
//        }
//        pushRecordMapper.insert(pushRecord);
    }

    /**
     * 按用户类型推送(极光推送)
     */
    @Override
    public void sendNotificationByUserType(Account loginUser, UserType userType, String title, String text,
                                           Map<String, Object> extendDataMap) {
//        String[] pushIds = userRemote.getPushIdsByUserType(userType).getData();
//        sendMessageByPushId(pushIds, title, text, extendDataMap);
    }

    /**
     * 按用户终端类型推送
     */
    @Override
    public void sendMessageByTerminal(PushRecord.PushTarget pushTarget, String title, String text,
                                      Map<String, Object> extendDataMap) {
//        //获取极光推送工具类
//        JpushClient jpushClient = JpushClient.getInstance(appkey, mastersecret);
//        //生成推送记录
//        PushRecord pushRecord = generatePushRecord(pushTarget, null, title, text, extendDataMap);
//        //发送
//        Map<String, Object> resultMap = null;
//        if (pushTarget == PushRecord.PushTarget.all) {
//            resultMap = jpushClient.sendToAll(pushRecord.getTitle(), pushRecord.getTitle(),
//                    pushRecord.getText(), pushRecord.getExtendData());
//        } else if (pushTarget == PushRecord.PushTarget.ios) {
//            resultMap = jpushClient.sendToAllIos(pushRecord.getTitle(), pushRecord.getTitle(),
//                    pushRecord.getText(), pushRecord.getExtendData());
//        } else if (pushTarget == PushRecord.PushTarget.android) {
//            resultMap = jpushClient.sendToAllAndroid(pushRecord.getTitle(), pushRecord.getTitle(),
//                    pushRecord.getText(), pushRecord.getExtendData());
//        }
//        pushRecord.setPushMsg((String) resultMap.get("pushResult"));
//        if ((boolean) resultMap.get("success")) {
//            pushRecord.setPushState(PushRecord.PushState.success);
//        } else {
//            pushRecord.setPushState(PushRecord.PushState.fail);
//            pushRecord.setSendNumber(pushRecord.getSendNumber() + 1);
//        }
//        pushRecordMapper.insert(pushRecord);
    }

    /**
     * 按用户标签(即用户类型)推送
     * 此功能要极光vip
     */
    @Override
    public void sendMessageByTags(String tags, String title, String text, Map<String, Object> extendDataMap) {
//        //获取极光推送工具类
//        JpushClient jpushClient = JpushClient.getInstance(appkey, mastersecret);
//        PushRecord pushRecord = new PushRecord();
//        pushRecord.setPushTarget(PushRecord.PushTarget.tags);
//        pushRecord.setPushState(PushRecord.PushState.save);
//        pushRecord.setPushParam(tags);
//        pushRecord.setTitle(title);
//        pushRecord.setText(text);
//        pushRecord.setSendTime(new Date());
//        pushRecord.setSendNumber(0);
//        pushRecord.setExtendData(JSONObject.toJSONString(extendDataMap));
//        //发送
//        Map<String, Object> resultMap = jpushClient.sendToAlias(aliasList, pushRecord.getTitle(),
//                pushRecord.getTitle(), pushRecord.getText(), pushRecord.getExtendData());
//        pushRecord.setPushMsg((String) resultMap.get("pushResult"));
//        if ((boolean) resultMap.get("success")) {
//            pushRecord.setPushState(PushRecord.PushState.success);
//        } else {
//            pushRecord.setPushState(PushRecord.PushState.fail);
//            pushRecord.setSendNumber(pushRecord.getSendNumber() + 1);
//        }
//        pushRecordDao.save(pushRecord);
    }

    /**
     * 更新推送标识
     */
    @Override
    public void updateAliasAndTag(Account loginUser, String pushId, String alias, String tag) {
        //获取极光推送工具类
        String platId = loginUser.getSuperiorPlatId();
        JpushClient jpushClient;
        if (loginUser.getUserType() == UserType.shipperUser) {
            jpushClient = JpushClient.getInstance(loginUser.getUserType(), getHatchJpush(platId).getShipperAppKey(), getHatchJpush(platId).getShipperMasterSecret());
        } else {
            jpushClient = JpushClient.getInstance(loginUser.getUserType(), getHatchJpush(platId).getTruckerAppKey(), getHatchJpush(platId).getTruckerMasterSecret());
        }
        jpushClient.updateAliasAndTag(pushId, alias, tag);
    }

    /**
     * 内部 生成推送记录
     *
     * @param pushParam 推送目标为ios/android/all传null
     */
    private PushRecord generatePushRecord(PushRecord.PushTarget pushTarget, String pushParam, String title,
                                          String text, Map<String, Object> extendDataMap) {
        PushRecord pushRecord = new PushRecord();
        pushRecord.setPushTarget(pushTarget);
        pushRecord.setPushState(PushRecord.PushState.save);
        pushRecord.setPushParam(pushParam);
        pushRecord.setTitle(title);
        pushRecord.setText(text);
        pushRecord.setSendTime(new Date());
        pushRecord.setSendNumber(0);
        pushRecord.setExtendData(JSONObject.toJSONString(extendDataMap));
        return pushRecord;
    }
}
